package com.itheima.service.impl.user;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.dao.user.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.User;
import com.itheima.service.user.UserService;
import com.itheima.utils.MD5Util;
import com.itheima.utils.SendEmail;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.itheima.utils.SmsDemo.sendSms;

/**
 * @author 郭文亮
 * @since 2021/11/4 15:37
 */
/**
 * @author 胡桂明
 * @since 2021/11/5 19:44
 */
@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Boolean findUserByUsernameAndPassword(User user) {
        // 散列算法使用MD5进行加密，加盐算法添加TeamGuoWl
        user.setPassword(MD5Util.md5(user.getPassword() + "TeamGuoWl"));
        List<User> getUser = userDao.findUserByUsernameAndPassword(user);
        return getUser.size() != 0;
    }

    @Override
    public String getTokenToRedis(User user) {
        String token = UUID.randomUUID().toString();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonUser = null;
        try {
            jsonUser = objectMapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 在redis创建token
        redisTemplate.opsForValue().set("user:token:" + token, jsonUser);
        // 设置过期时间为7天
        redisTemplate.expire("user:toke:" + token, 7, TimeUnit.DAYS);
        return token;
    }

    @Override
    public String getCode(String email) {
        // 生成随机数
        String code = getRandomString(6);
        System.out.println("aaaaaaaaaaa"+code);
        try {
            SendEmail.sendMail(email,code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return code;
    }

    @Override
    public Boolean register(User user) {
        // 散列算法使用MD5进行加密，加盐算法添加TeamGuoWl
        user.setPassword(MD5Util.md5(user.getPassword() + "TeamGuoWl"));
        return userDao.addUser(user) > 0;
    }

    /**
     * 随机产生a-zA-Z0-9的字符串，长度为length
     *
     * @param length 需要生成的验证码长度
     * @return 生成的验证码
     */
    public static String getRandomString(int length) {
        //产生随机数
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        //循环length次
        for (int i = 0; i < length; i++) {
            //产生0-2个随机数，既与a-z，A-Z，0-9三种可能
            int number = random.nextInt(3);
            long result;
            switch (number) {
                //如果number产生的是数字0；
                case 0:
                    //产生A-Z的ASCII码
                    result = Math.round(Math.random() * 25 + 65);
                    //将ASCII码转换成字符
                    sb.append(((char) result));
                    break;
                case 1:
                    //产生a-z的ASCII码
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append(((char) result));
                    break;
                case 2:
                    //产生0-9的数字
                    sb.append((new Random().nextInt(10)));
                    break;
                default:
                    break;
            }
        }
        return sb.toString();
    }

    /**
     * 新增
     * @param user   传入对象数据
     * @return          返回结果
     */
    @Override
    public boolean save(User user) {
        return userDao.save(user);
    }

    /**
     * 删除
     * @param id    删除条件
     * @return      返回结果
     */
    @Override
    public boolean delete(int id) {
        return userDao.delete(id);
    }

    /**
     * 修改
     * @param user   传入对象数据
     * @return      返回结果
     */
    @Override
    public boolean update(User user) {
        return userDao.update(user);
    }

    /**
     * 按ID查找-修改用
     * @param id    查询条件
     * @return      返回查询结果
     */
    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }

    /**
     * 查询全部
     * @return  返回查询结果
     */
    @Override
    public PageResult findAll(QueryPageBean queryPageBean) {
        //分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //获取dao层数据
        List<User> userList = userDao.findAll(queryPageBean.getQueryString());
        //封装到PageInfo
        PageInfo pageInfo = new PageInfo(userList);
        //封装到PageResult
        PageResult pageResult = new PageResult(pageInfo.getTotal(), pageInfo.getList());
        return pageResult;
    }
}
